package org.iogame.controller;

import lombok.extern.slf4j.Slf4j;
import org.iogame.dto.Result;
import org.iogame.socket.IoGameSocket;
import org.iogame.socket.VueRouter;
import org.springframework.stereotype.Service;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;

/**
 * @author lc
 * @since 2022/6/9
 */
@Service
@ServerEndpoint(value = "/game/{userId}")
@Slf4j
public class SocketServer {

    /** 服务器连接数 */
    private static final HashMap<String,Session> SERVER_MAP = new HashMap<>();

    public static String  getUserId(Session session){
        return session.getRequestURI().getPath().replace("/game/", "");
    }


    @OnOpen//连接成功时调用的方法
    public void onOpen(Session session)  {
        String userId = getUserId(session);
        SERVER_MAP.put(userId, session);
        sendAllMessage(Result.buildResult(VueRouter.SERVER_COUNT, SERVER_MAP.size()));
        log.info("总链接数: {}", SERVER_MAP.size());
    }

    @OnClose //连接关闭时调用的方法
    public void onClose(Session session) throws IOException {
        close(session);
        log.info("连接关闭");
    }

    @OnMessage //收到客户端消息时调用的方法
    public void onMessage(String message, Session session) throws IOException {
        log.info("客户端消息: {}",message);
        //sendAllMessage(message);
    }

    @OnError // 出现异常时调用的方法
    public void onError(Session session, Throwable error) throws IOException {
        close(session);
        log.info("错误：{}",error.getMessage());
    }

    public void close(Session session) throws IOException {
        String userId = getUserId(session);
        SERVER_MAP.remove(userId);
        IoGameSocket.close(userId);

        sendAllMessage(Result.buildResult(VueRouter.SERVER_COUNT, SERVER_MAP.size()));
        session.close();
    }

    /** 向所有人发送消息 */
    public static void sendAllMessage(String message) {
        try {
            for (Session value : SERVER_MAP.values()) {
                value.getBasicRemote().sendText(message);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    /** 发送消息 **/
    public static void sendByUserIdMessage(String message, String userId)  {
        try {
            Session session = SERVER_MAP.get(userId);
            if (session != null) {
                session.getBasicRemote().sendText(message);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


}
